var myApp = angular.module('myCoolApp', ['bootstrap.tabset', 'ngTable', 'ngResource', 'ngAnimate']);
myApp.factory('tabulationFactory', function ($http) {
    var data = {'command': 'getTabs'};
    return {
        getTabNames: function () {
            return $http.post('/ajax/processor', data);
        }
    };
});
myApp.factory('removeService', function($http){

    var serviceInstance = {};
    serviceInstance.removeEntity = function(originatorKey, callback) {
        $http({
            method: "POST",
            url: "/ajax/processor",
            data: {
                'command' : 'removeEntity',
                's_key' : originatorKey
            }
        }).then(callback());
    };
    return serviceInstance;
});
myApp.controller('tabController', function ($scope, tabulationFactory, $rootScope) {
//    $scope.tabContent = tabulationFactory.getTabNames();
    $scope.tabContent = [];
//    $rootScope.loading = false;
    var handleSuccess = function (data) {
        $scope.tabContent = data[0];
        $scope.logoutUrl = data[1];
        $rootScope.loading = false;
        $scope.unregisterController(this);
    };
    $scope.registeredControllers = [this];

    $scope.registerController = function(controller) {
        $scope.registeredControllers.push(controller);
    };

    $scope.unregisterController = function(controller) {
        var index = $scope.registeredControllers.indexOf(controller);
        $scope.registeredControllers.splice(index, 1);
    };

    tabulationFactory.getTabNames().success(handleSuccess);
    $scope.$on('manualEvent', function(args, data){
        $scope.$broadcast(data['eventType'], data['payload']);
    });
});
myApp.controller('StudentListController', function ($scope, $http) {
    $scope.registerController(this);
    $http.post('/ajax/processor', {'command': 'getStudents'})
        .then(function (res) {
            $scope.students = res.data[1];
            $scope.unregisterController(this);
        });
});
myApp.controller('AchievementTypeListController', function ($scope, $http) {
    $scope.registerController(this);
    $http.post('/ajax/processor', {'command': 'getATypes'})
        .then(function (res) {
            $scope.types = res.data[0];
            $scope.effects = res.data[1];
            $scope.unregisterController(this);
        });
});
myApp.controller('GroupListController', function ($scope, $http) {
    $http.post('/ajax/processor', {'command': 'getGroups'})
        .then(function (res) {
            $scope.groups = res.data;
        });
});
myApp.controller('GWTDivController', function ($scope, $compile) {
    $scope.registerController(this);
    $scope.recompile = function () {
        $compile($("#main").contents())($scope);
        $scope.unregisterController(this);
    };
    $scope.$on('resetImage', function(args, data){
        replaceUrl(data);
    });
    $scope.replaceKey = '';
    $scope.replaceId = '';
    $scope.isPositive = -1;
    $scope.selectedType = '';

    $scope.$on('replaceImage', function(args, data){
        replaceUrl(data[0], data[2]);
        $scope.replaceKey = data[1];
        $scope.replaceId = data[3];
        $scope.isPositive = data[4];
        $scope.selectedType = data[5];
    });

    $scope.releaseReplace = function(){
        $scope.replaceKey='';
        $scope.replaceId='';
        $scope.isPositive = -1;
        $scope.selectedType = '';
    }
});
myApp.controller('CuratorFormController', function ($scope, $http) {
    $scope.submit = function () {
        $http({
            method: 'POST',
            url: '/ajax/processor?command=addCurator',
            data: $scope.curator
        }).success(function (data, status, headers, config) {
            $scope.$broadcast('reloadTable');
        });
    };
});
myApp.controller('StudentFormController', function ($scope, $http) {
    $scope.submit = function () {
        $http({
            method: 'POST',
            url: '/ajax/processor?command=addStudent',
            data: $scope.student
        }).success(function (data, status, headers, config) {
            $scope.$broadcast('reloadTable');
        });
    };
});
myApp.controller('CuratorTableController', function ($scope, $timeout, $resource, ngTableParams, removeService) {
    var source = $resource('/ajax/processor', {'command': 'getCurators'}, {save: {method: 'POST', isArray: true}});
    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 10
    }, {
        counts: [],
        total: 0,           // length of data
        getData: function ($defer, params) {
            // ajax request to api
            source.save(params.url(), function (data) {    //POST method?
                $timeout(function () {
                    // update table params
                    var total = data[0]['total'];
                    params.total(total);
                    // set new data
                    var outputData = data[1];
                    $defer.resolve(outputData);
                }, 0);
            });
        }, $scope: {$data: {}}
    });
    $scope.$on('reloadTable', function () {
        $scope.tableParams.reload();
    }, true);
    $scope.deleteEntity = function(entity){
        removeService.removeEntity(entity.datum.key, function(){
            $timeout(function(){
                $scope.tableParams.reload();
            }, 100);
        })
    }
});
myApp.controller('StudentTableController', function ($scope, $timeout, $resource, ngTableParams, removeService) {
    var source = $resource('/ajax/processor', {
            'command': 'getStudents'
        },
        {
            save: {method: 'POST', isArray: true}
        });
    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 15
    }, {
        counts: [],
        total: 0,           // length of data
        getData: function ($defer, params) {
            // ajax request to api
            source.save(params.url(), function (data) {    //POST method?
                $timeout(function () {
                    // update table params
                    var total = data[0]['total'];
                    params.total(total);
                    // set new data
                    var outputData = data[1];
                    $defer.resolve(outputData);
                }, 0);
            });
        }
    });
    $scope.$on('reloadTable', function () {
        $scope.tableParams.reload();
    }, true);
    $scope.deleteEntity = function(entity){
        removeService.removeEntity(entity.datum.key, function(){
            $timeout(function(){
                $scope.tableParams.reload();
            }, 100);
        })
    }
});
myApp.controller('AchievementTableController', function ($scope, $timeout, $resource, $http, ngTableParams, removeService) {
    $scope.userName = '';

    var source = $resource('/ajax/processor', {
            'command': 'getAchievements'
        },
        //var source = $resource('/student', {},
        {
            save: {method: 'POST', isArray: true}
        });
    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 7
    }, {
        counts: [],
        total: 0,           // length of data
        getData: function ($defer, params) {
            // ajax request to api
            source.save(params.url(), function (data) {    //POST method?
                $timeout(function () {
                    // update table params
                    $scope.userName = data[2]['user'];
                    var total = data[0]['total'];
                    params.total(total);
                    // set new data
                    var outputData = data[1];
                    $defer.resolve(outputData);
                }, 0);
            });
        }
    });
    $scope.deleteEntity = function(entity){
        removeService.removeEntity(entity.datum.key, function(){
            $timeout(function(){
                $scope.tableParams.reload();
            }, 100);
        })
    };
    $scope.approve = function(key, proposedBy) {
        var data = {
            'command' : 'approveAchievement',
            'user' : proposedBy,
            'key' : key
        };
        $http({
            'method' : 'POST',
            'url' : '/ajax/processor',
            'data' : data
        }).success($scope.tableParams.reload());
    }
});
myApp.run(function ($rootScope) {
    $rootScope.showDiv = true;
//    $rootScope.loading = true;
});
